package com.acoreful.acf2admin.web.interceptor;

import java.lang.reflect.Method;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.acoreful.acf2admin.web.annotation.Token;

/**
 * 是否重复提交
 * @author AcoreHeng
 *
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
	private Logger logger=LoggerFactory.getLogger(TokenInterceptor.class);
	/**
	 * 
	 */
	private final String SESSION_TOKEN="token";
	private final String REQ_PARAMS_TOKEN=SESSION_TOKEN;
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	logger.info("URL:{}",request.getRequestURI());
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Token annotation = method.getAnnotation(Token.class);
            if (annotation != null) {
                boolean needSaveSession = annotation.save();
                if (needSaveSession) {
                    request.getSession(false).setAttribute(SESSION_TOKEN, UUID.randomUUID().toString());
                }
                boolean needRemoveSession = annotation.remove();
                if (needRemoveSession) {
                    if (isRepeatSubmit(request)) {
                        return false;
                    }
                    request.getSession(false).removeAttribute(SESSION_TOKEN);
                }
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }
 
    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) request.getSession(false).getAttribute(SESSION_TOKEN);
        if (serverToken == null) {
            return true;
        }
        String clinetToken = request.getParameter(REQ_PARAMS_TOKEN);
        if (clinetToken == null) {
            return true;
        }
        if (!serverToken.equals(clinetToken)) {
            return true;
        }
        return false;
    }
    @Override
    public void postHandle(HttpServletRequest request,
    		HttpServletResponse response, Object handler,
    		ModelAndView modelAndView) throws Exception {
    	//logger.info("------------------------------------");
    	super.postHandle(request, response, handler, modelAndView);
    	String ajaxToken=UUID.randomUUID().toString();
    	response.addHeader("o-ajax-token", ajaxToken);
    }
    @Override
    public void afterCompletion(HttpServletRequest request,
    		HttpServletResponse response, Object handler, Exception ex)
    		throws Exception {
    	//logger.info("{}------------------------------------",response.getHeaders("o-ajax-token"));
    	String ajaxToken=UUID.randomUUID().toString();
    	response.addHeader("o-ajax-token", ajaxToken);
    	//logger.info("{}------------------------------------",response.getHeaders("o-ajax-token"));
    	
    	super.afterCompletion(request, response, handler, ex);
    }
}